<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;


// 兑换记录
class Exchange extends BaseController
{
    public function index()
    {
        $goods = Db::name('integral_goods')
            ->where('delete', '=', 1)
            ->where('status', '=', 1)
            ->select();
        View::assign('goods', $goods);
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        $where = [];
        $get = $request->param();

        if (isset($get['goods_id'])) {
            if (!empty($get['goods_id'])) {
                $where[] = ['c.id', '=', $get['goods_id']];
            }
        }

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['b.name|b.userid', 'like', '%'.$get['title'].'%'];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }


        if (isset($get['is_deliver'])) {
            if (!empty($get['is_deliver'])){
                if ($get['is_deliver'] == 1) {
                    $where[] = ['a.is_deliver', '=', 0];
                }else{
                    $where[] = ['a.is_deliver', '=', 1];
                }
            }
        }


        session('exchange_where', $where);

        $total = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_members b','a.uid = b.id','left')
            ->join('o_integral_goods c','a.goods_id = c.id','left')
            ->where('a.goods_id','>',0)
            ->where($where)
            ->count();

        $rows = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_members b','a.uid = b.id','left')
            ->join('o_integral_goods c','a.goods_id = c.id','left')
            ->where('a.goods_id','>',0)
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('c.title as goods_name, c.type as goods_type, c.status as goods_status, c.integral, b.userid, b.name, a.id, a.add_time, a.express, a.is_deliver, a.no')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }



    // 导入
    public function import()
    {
        return View::fetch();
    }




    // 执行导入
    public function batchToggleExpress(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);

            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {

                $update = [];

                if (isset($value[0])) {
                    $update['express_id'] = $value[0];
                } else {
                    return $this->outputAjax('快递公司缺失', 2);
                }

                if (isset($value[1])) {
                    $no = convert_scientific_number_to_normal($value[1]);
                } else {
                    return $this->outputAjax('订单号缺失', 2);
                }

                if (isset($value[2])) {
                    $update['express_number'] = convert_scientific_number_to_normal($value[2]);
                } else {
                    return $this->outputAjax('快递单号缺失', 2);
                }

                $update['is_deliver'] = 1; //导入默认为老员工

                $f = Db::name('integral_detail')->where('no', '=', $no)->update($update);
                if ($f) {
                    $i++;
                }
            }


            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }


    public function release(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->param('id');
        $express = Db::name('express')->select()->toArray();

        View::assign('express',$express);
        View::assign('id',$id);
        return View::fetch();
    }


    public function send(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        if (empty($post['express_id'])) {
            return $this->outputAjax('请选择快递公司');
        }
        
        if (empty($post['express_number'])) {
            return $this->outputAjax('请填写快递单号');
        }

        try {

            $update = array(
                'express_id' => $post['express_id'],
                'express_number' => $post['express_number'],
                'is_deliver' => 1,
            );
            if (!Db::name('integral_detail')->where('id', '=', $post['id'])->update($update)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }

    }

    public function export()
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        ob_end_clean ();

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '兑换记录报表'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['订单号', '工号', '姓名', '兑换商品', '商品类型', '消耗积分', '状态', '兑换时间', '姓名', '手机', '地址']);



        $where = session('exchange_where') ? : [];

        $total = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_members b','a.uid=b.id','left')
            ->join('o_integral_goods c','a.goods_id=c.id','left')
            ->where('a.goods_id','>',0)
            ->where($where)
            ->count();

        $nums = 1000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $dataArray = Db::table('o_integral_detail')
                ->alias('a')
                ->join('o_members b','a.uid=b.id','left')
                ->join('o_integral_goods c','a.goods_id=c.id','left')
                ->where('a.goods_id','>',0)
                ->where($where)
                ->order('a.add_time', 'desc')
                ->field('c.title as goods_name, c.type as goods_type, c.status as goods_status, c.integral, b.userid, b.name, a.id, a.add_time, a.express, a.is_deliver, a.no')
                ->limit($start, $nums)
                ->select()->toArray();


            foreach ($dataArray as &$v) {
                if ($v['express']) {
                    $res = is_null(json_decode($v['express'], true));
                    if ($res) {
                        $express_json = json_decode(decrypts($v['express']), true);

                        $res1 = is_array($express_json);
                        if (!$res1) {
                            $express = json_decode($express_json,true);
                        } else {
                            $express = $express_json;
                        }

                    } else {
                        $express = json_decode($v['express'],true);
                    }

                    $express_info1 = $express['name'];
                    $express_info2 = $express['phone'];
                    $express_info3 = $express['address'];
                } else {
                    $express_info1 = '';
                    $express_info2 = '';
                    $express_info3 = '';
                }

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }


                $arr = [
                    "'".$v['no'],
                    $userid,
                    $v['name'],
                    $v['goods_name'],
                    $v['goods_type'] == 1 ? '实物':'虚拟',
                    $v['integral'],
                    $v['is_deliver'] == 0 ? '新订单':'已发货',
                    date('Y-m-d H:i:s', $v['add_time']),
                    $express_info1,
                    $express_info2,
                    $express_info3
                ];
                fputcsv($fp, $arr);
            }

            //每1千条数据就刷新缓冲区
            flush();
        }
    }
}